package com.ruoyi.common.utils.http;

import com.ruoyi.common.json.JSON;
import com.ruoyi.common.json.JSONObject;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;

public class IAMHttpUtils {
    public final static String TYPE_FORM = "application/x-www-form-urlencoded";
    public final static String TYPE_JSON = "application/json";
    public final static String TYPE_XML = "application/xml";
    public final static String TYPE_FILE = "multipart/form-data";


    public static JSONObject HttpsUtil(String Url, String Method, String Output) throws Exception{
        JSONObject jsonObject = null;
        URL conn_url =  new URL(Url);
        HttpURLConnection conn = (HttpsURLConnection)conn_url.openConnection();
        conn.setRequestMethod(Method);
        conn.setReadTimeout(5000);
        conn.setConnectTimeout(5000);
        conn.connect();
        //output获取access_token是不会用到
        if(Output != null){
            OutputStream outputstream =conn.getOutputStream();
            //字符集，防止出现中文乱码
            outputstream.write(Output.getBytes("UTF-8"));
            outputstream.close();
        }
        //正常返回代码为200
        if(conn.getResponseCode()==200){
            InputStream stream = conn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(stream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            StringBuffer buffer = new StringBuffer();
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            stream.close();
            conn.disconnect();
            jsonObject = JSON.unmarshal(buffer.toString(), JSONObject.class);
        }
        System.out.println(conn.getResponseCode());
        return jsonObject;
    }
    /**
     * 利用URL发起POST请求，并接收返回信息
     * @param url 请求URL
     * @return 响应内容
     * @throws Exception
     */
    public static String doPost(String url, String params) throws Exception {
        return doPost(url, params, "application/x-www-form-urlencoded");
    }

    /**
     * 利用URL发起POST请求，并接收返回信息
     * @param url 请求URL
     * @return 响应内容
     * @throws Exception
     */
    public static String doPost(String url, Map<String, String> params) throws Exception {
        return doPost(url, params, "application/x-www-form-urlencoded");
    }

    /**
     * 利用URL发起POST请求，并接收返回信息
     * @param url 请求URL
     * @param contentType 请求类型
     * @return 响应内容
     * @throws Exception
     */
    public static String doPost(String url, String params, String contentType) throws Exception {
        StringBuffer sb = new StringBuffer();
        try {
            URL urls = new URL(url);
            HttpURLConnection uc = (HttpURLConnection) urls.openConnection();
            uc.setRequestMethod("POST");
            uc.setRequestProperty("content-type", contentType);
            uc.setRequestProperty("charset", "UTF-8");
            uc.setDoOutput(true);
            uc.setDoInput(true);
            uc.setReadTimeout(30000);
            uc.setConnectTimeout(30000);
            OutputStream os = uc.getOutputStream();
            DataOutputStream dos = new DataOutputStream(os);
            dos.write(params.getBytes("utf-8"));
            dos.flush();
            os.close();
            BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream(), "utf-8"));
            String readLine = "";
            while ((readLine = in.readLine()) != null) {
                sb.append(readLine);
            }
            in.close();
        } catch (Exception e) {
            throw e;
        }
        return sb.toString();
    }
    /**
     * 利用URL发起POST请求，并接收返回信息
     * @param url 请求URL
     * @param contentType 请求类型
     * @return 响应内容
     * @throws Exception
     */
    public static String doPost(String url, Map<String, String> params, String contentType) throws Exception {
        StringBuffer sb = new StringBuffer();
        try {
            URL urls = new URL(url);
            HttpURLConnection uc = (HttpURLConnection) urls.openConnection();
            uc.setRequestMethod("POST");
            uc.setRequestProperty("content-type", contentType);
            uc.setRequestProperty("charset", "UTF-8");
            uc.setDoOutput(true);
            uc.setDoInput(true);
            uc.setReadTimeout(30000);
            uc.setConnectTimeout(30000);
            OutputStreamWriter osw = new OutputStreamWriter(uc.getOutputStream(), "UTF-8");
            osw.write(getUrlParamsFromMap(params));
            osw.flush();
            osw.close();
            BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream(), "utf-8"));
            String readLine = "";
            while ((readLine = in.readLine()) != null) {
                sb.append(readLine);
            }
            in.close();
        } catch (Exception e) {
            throw e;
        }
        return sb.toString();
    }

    /**
     * 利用URL发起GET请求，并接收返回信息
     * @param url 请求URL
     * @return 响应内容
     * @throws Exception
     */
    public static String doGet(String url, String params) throws Exception {
        return doGet(url, params, "application/x-www-form-urlencoded");
    }

    /**
     * 利用URL发起GET请求，并接收返回信息
     * @param url 请求URL
     * @return 响应内容
     * @throws Exception
     */
    public static String doGet(String url, Map<String, String> params) throws Exception {
        return doGet(url, params, "application/x-www-form-urlencoded");
    }

    /**
     * 利用URL发起GET请求，并接收返回信息
     * @param url 请求URL
     * @param contentType 请求类型
     * @return 响应内容
     * @throws Exception
     */
    public static String doGet(String url, String params, String contentType) throws Exception {
        StringBuffer sb = new StringBuffer();
        try {
            URL urls = new URL(url+"?"+params);
            HttpURLConnection uc = (HttpURLConnection) urls.openConnection();
            uc.setRequestMethod("GET");
            uc.setRequestProperty("content-type", contentType);
            uc.setRequestProperty("charset", "UTF-8");
            uc.setReadTimeout(30000);
            uc.setConnectTimeout(30000);
            BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream(), "utf-8"));
            String readLine = "";
            while ((readLine = in.readLine()) != null) {
                sb.append(readLine);
            }
            in.close();
        } catch (Exception e) {
            throw e;
        }
        return sb.toString();
    }

    /**
     * 利用URL发起免SSL证书校验GET请求，并接收返回信息
     * @param url 请求URL
     * @return 响应内容
     * @throws Exception
     */
    public static String doGet(String url) throws Exception {
        StringBuffer sb = new StringBuffer();
        try {
            URL urls = new URL(url);
            HttpsURLConnection conn = (HttpsURLConnection) urls.openConnection();
            // 新增部分
            conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
            conn.connect();
            InputStream is = conn.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            br.close();
            is.close();
        }catch (Exception e){
            throw e;
        }
        return sb.toString();
    }

    public static String doGetWithAuth(String url,String auth) throws Exception {
        StringBuffer sb = new StringBuffer();
        try {
            URL urls = new URL(url);
            HttpsURLConnection conn = (HttpsURLConnection) urls.openConnection();
            conn.setRequestProperty("Authorization",auth);
            // 新增部分
            conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
            conn.connect();
            InputStream is = conn.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            br.close();
            is.close();
        }catch (Exception e){
            throw e;
        }
        return sb.toString();
    }
    /**
     * 利用URL发起GET请求，并接收返回信息
     * @param url 请求URL
     * @param contentType 请求类型
     * @return 响应内容
     * @throws Exception
     */
    public static String doGet(String url, Map<String, String> params, String contentType) throws Exception {
        StringBuffer sb = new StringBuffer();
        try {
            URL urls = new URL(url+"?"+getUrlParamsFromMap(params));
            HttpURLConnection uc = (HttpURLConnection) urls.openConnection();
            uc.setRequestMethod("GET");
            uc.setRequestProperty("content-type", contentType);
            uc.setRequestProperty("charset", "UTF-8");
            uc.setReadTimeout(30000);
            uc.setConnectTimeout(30000);
            BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream(), "utf-8"));
            String readLine = "";
            while ((readLine = in.readLine()) != null) {
                sb.append(readLine);
            }
            in.close();
        } catch (Exception e) {
            throw e;
        }
        return sb.toString();
    }

    /**
     * 将map转换成url参数格式: name1=value1&name2=value2
     *
     * @param map
     * @return
     */
    private static String getUrlParamsFromMap(Map<String, String> map) {
        try {
            if (null != map) {
                StringBuilder stringBuilder = new StringBuilder();
                for (Map.Entry<String, String> entry : map.entrySet()) {
                    stringBuilder.append(URLEncoder.encode(entry.getKey(), "UTF-8"))
                            .append("=")
                            .append(URLEncoder.encode(entry.getValue(), "UTF-8"))
                            .append("&");
                }
                String content = stringBuilder.toString();
                if (content.endsWith("&")) {
                    content = content.substring(0, content.length() - 1);
                }
                return content;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static class TrustAnyHostnameVerifier implements HostnameVerifier {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    }
}
